// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

#nullable enable

using System;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Resources;

namespace NuGet.Protocol.Providers
{
    /// <summary>NuGet.Protocol resource provider for <see cref="IVulnerabilityInfoResource"/> in V3 HTTP feeds.</summary>
    /// <remarks>When successful, returns an instance of <see cref="VulnerabilityInfoResourceV3"/>.</remarks>
    public sealed class VulnerabilityInfoResourceV3Provider : ResourceProvider
    {
        /// <summary>Create an instance of the resource provider.</summary>
        public VulnerabilityInfoResourceV3Provider()
            : base(typeof(IVulnerabilityInfoResource), nameof(VulnerabilityInfoResourceV3Provider), NuGetResourceProviderPositions.Last)
        {
        }

        /// <inheritdoc cref="ResourceProvider.TryCreate(SourceRepository, CancellationToken)"/>
        public override async Task<Tuple<bool, INuGetResource?>> TryCreate(SourceRepository source, CancellationToken token)
        {
            var serviceIndexResource = await source.GetResourceAsync<ServiceIndexResourceV3>(token);
            Uri? baseUri = serviceIndexResource?.GetServiceEntryUri(ServiceTypes.VulnerabilityInfo);
            if (baseUri != null)
            {
                var resource = new VulnerabilityInfoResourceV3(source);
                return new Tuple<bool, INuGetResource?>(true, resource);
            }

            return new Tuple<bool, INuGetResource?>(false, null);
        }
    }
}
